//session
const sessionData = {
    expiration: 60 * 60 * 1000, // 一个小时
    get: function(key) {
        return _get({ type: 'session', key })
    },
    set: function(key, value, expiration) {
        let _expiration = expiration || this.expiration;
        return _set({ type: 'session', key, value, expiration: _expiration })
    },
    clear: function(key) {
        return _clear({ type: 'session', key })
    }
}

// 获取本地缓存
function _get({ type, key }) {
    if (!key) return null;
    let storageValue = type == 'local' ?
        localStorage.getItem(key) : // localStorage
        sessionStorage.getItem(key); // sessionStorage
    if (!storageValue) return null;
    let storageValueObj = _tryParseJson(storageValue); //转json
    let localValue = _tryParseJson(storageValueObj.value); //存储的数据
    let localExpiration = storageValueObj.expiration; //过期时间
    let nowTime = new Date().getTime(); //当前时间
    if (nowTime > localExpiration) { //已过期
        _clear({ type, key }); //清除
        return null
    }
    return localValue;
}

// 存储本地缓存
function _set({ type, key, value, expiration }) {
    if (!key) return null;
    let storageValue = _tryParseString({
        value: _tryParseString(value),
        expiration: new Date().getTime() + expiration
    })
    type == 'local' ?
        localStorage.setItem(key, storageValue) : // localStorage
        sessionStorage.setItem(key, storageValue) // sessionStorage
    return null
}

// 删除本地缓存
function _clear({ type, key }) {
    if (!key) return null;
    type == 'local' ?
        localStorage.removeItem(key) :
        sessionStorage.removeItem(key);
    return null
}

// 转json
function _tryParseJson(value) {
    try {
        return JSON.parse(value);
    } catch (e) {
        return value
    }
}

// 转字符串
function _tryParseString(obj) {
    if (typeof obj == 'object') {
        return JSON.stringify(obj)
    }
    return obj
}
export {
    sessionData
}